package com.tarena.lbs.basic.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.basic.dao.mapper.AreaMapper;
import com.tarena.lbs.basic.dao.repository.AreaRepository;
import com.tarena.lbs.basic.pojo.po.AreaPO;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class AreaRepositoryImpl implements AreaRepository {
    @Autowired
    private AreaMapper areaMapper;
    @Override
    public List<AreaVO> queryProvinces() {
        List<AreaVO> areaVOS = new ArrayList<>();
        // 查询所有省份
        QueryWrapper<AreaPO> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<AreaPO> areaPOS = areaMapper.selectList(wrapper);
        log.debug("转换为VO前areaPOS:{}", areaPOS);
        // 转换为VO
        for (AreaPO areaPO : areaPOS) {
            AreaVO areaVO = new AreaVO();
            BeanUtils.copyProperties(areaPO, areaVO);
            log.debug("BeanUtils转换为VO后areaVO:{}", areaVO);
            areaVOS.add(areaVO);
        }
        log.debug("转换为VO后areaVOS:{}", areaVOS);
        //查询所有省份的子区域并为每个省份添加子区域
        /*for (AreaVO areaVO : areaVOS) {
            List<AreaVO> childrenVOS = queryChildren(areaVO.getId().intValue());
            areaVO.setChildren(childrenVOS);
        }
        log.debug("添加子区域后areaVOS:{}", areaVOS);*/
        return areaVOS;
    }

    @Override
    public List<AreaVO> queryChildren(Integer parentId) {
        List<AreaVO> areaVOS = new ArrayList<>();
        QueryWrapper<AreaPO> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<AreaPO> areaPOS = areaMapper.selectList(wrapper);
        log.debug("Children转换为VO前childrenAreaPOS:{}", areaPOS);
        // 转换为VO
        for (AreaPO areaPO : areaPOS) {
            AreaVO areaVO = new AreaVO();
            BeanUtils.copyProperties(areaPO, areaVO);
            log.debug("BeanUtils转换为VO后childrenAreaVO:{}", areaVO);
            areaVOS.add(areaVO);
        }
        log.debug("Children转换为VO后childrenAreaVOS:{}", areaVOS);
        return areaVOS;
    }
}
